package com.example.ktapplication.utils

import android.content.Context
import android.content.res.Resources
import com.example.ktapplication.activity.WebViewActivity
import com.example.ktapplication.bean.base.BaseRepo
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

fun Context.jumpUrl(url: String, title: String = "") {
    WebViewActivity.start(this, url, title)
}

fun <T> ioSwitchMain(
    block: suspend () -> T,
    result: suspend (t: T) -> Unit
) {
    GlobalScope.launch(Dispatchers.IO) {
        val data = block.invoke()
        withContext(Dispatchers.Main) {
            result.invoke(data)
        }
    }
}

// 将 dp 转换为 px 的扩展函数
fun Int.toPx(): Int {
    val density = Resources.getSystem().displayMetrics.density
    return (this * density).toInt()
}

fun <T> httpRequest(
    block: suspend () -> BaseRepo<T>,
    result: suspend (t: T) -> Unit,
    error: suspend (Int, String) -> Unit,
    complete: suspend () -> Unit
) {
    GlobalScope.launch(Dispatchers.Main) {
        val t: T
        val data: BaseRepo<T>
        try {
            data = block()
            t = data.data
            LogHelper.e("httpRequest data:${Gson().toJson(data)}")
            if (data.errorCode == 0) {
                result(t)
            } else {
                error(data.errorCode, data.errorMsg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            try {
                error(-1, "${e.message}")
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } finally {
            try {
                complete.invoke()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

/**
 * 对象转json字符串
 */
fun Any.toJson(): String {
    return Gson().toJson(this)
}